﻿using System;
using Transformable_Engine_v2.Engine.Helper;

namespace Transformable_Engine_v2.Engine.Time
{
    public class Timer
    {
        private double _timeToLive;
        private double _timeElapsed;
        private readonly bool _isLooping;
        private readonly Action _methodToCall;

        public int AlarmCount { get; private set; }

        private bool _isStarted;

        public Timer(double timeToLive, bool isLooping, Action methodToCall)
        {
            _timeToLive = timeToLive;
            _isLooping = isLooping;
            _methodToCall = methodToCall;
            AlarmCount = 0;
            _isStarted = false;
            _isAlive = true;
        }

        public double PercentageElapsed
        {
            get 
            {
                return (_timeElapsed / _timeToLive).Clamp(0, 1); 
            }
        }

        public bool IsStarted
        {
            get { return _isStarted; }
        }

        public void Reset(double timeToLive)
        {
            _timeToLive = timeToLive;
            Reset();
        }

        public void Reset()
        {
            AlarmCount = 0;
            Start();
        }

        public void Start()
        {
            _timeElapsed = 0;
            _isStarted = true;
        }
        public Timer AutoStart()
        {
            Start();
            return this;
        }

        public void Stop()
        {
            _isStarted = false;
        }

        public void FixedStepUpdate(TimeSpan gameTime)
        {
            if (_isStarted)
            {
                _timeElapsed += gameTime.TotalMilliseconds;

                if (_timeElapsed >= _timeToLive)
                {
                    AlarmCount++;

                    if (_isLooping)
                    {
                        _timeElapsed -= _timeToLive;
                        Start();
                    }
                    else
                    {
                        _isStarted = false;
                    }

                    if (_methodToCall != null)
                        _methodToCall();
                }
            }
        }

        private bool _isAlive;
        public bool IsAlive()
        {
            return _isAlive;
        }

        public void Die()
        {
            _isAlive = false;
            _isStarted = false;
        }

        public void UnloadContent()
        {
        }
    }
}